package com.projektio.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;


public class RectPixelCountAlgorithm extends ImageTranslationAlgorithm
{
	private int rectSize = 40;
	@Override
	public ImageAttribute[] calculateImageAttributes(Image image) 
	{
		MatrixFilter filter = new MatrixFilter(new int[][]{{-1,-1,-1}, {-1,8,-1}, {-1,-1,-1}}, 1);
			
		Image image2 = image.getGrayScaleImage();
		image2 = image2.getBinaryImage(image2.getOtsuThreshold());
		image2 = filter.doFiltering(image2);
		int rows = (image2.getHeight()/rectSize);//+1;
		int cols = (image2.getWidth()/rectSize);//+1;
		ImageAttribute[] attributes = new ImageAttribute[rows*cols];
		int attCount = 0, x, y; 
		short[] color;
		int[] mid = new int[3];
		for(int r = 0; r < rows; r++)
		{
			for(int c = 0; c < cols; c++)
			{
				int white = 0, black = 0;
				for(int i = 0; i < rectSize; i++)
				{
					for(int j = 0; j < rectSize; j++)
					{
						x = c*rectSize + j; y = r*rectSize + i;
						if(image2.getPixel(x, y)[0] == 0)
						{
							black++;
						}
						else
						{
							white++;
						}
						color = image.getPixel(x, y);
						for(int k = 0; k < 3; k++) mid[k] += color[k];
					}
				}
				color = new short[]{(short)(mid[0]/1600), (short)(mid[1]/1600), (short)(mid[2]/1600)};
				attributes[attCount++] = new ImageAttribute(r, c, white, black, color);
				mid = new int[3];
			}
		}
		
		return attributes;
	}
	
	
	public static void main(String ... args)
	{
		BitmapImageIO bir = new BitmapImageIO();
		Image image;
		RectPixelCountAlgorithm rpca = new RectPixelCountAlgorithm();
		ImageAttribute[] attrs;
		
		try 
		{
			image = bir.readImage(new FileInputStream("E:/testImageBig.bmp"));
			int rows = (image.getHeight()/40);//+1;
			int cols = (image.getWidth()/40);//+1;
			attrs = rpca.calculateImageAttributes(image);
			Image test = new Image( cols, rows, 24);
			for(int i = 0; i < attrs.length; i++)
			{
				test.setPixel(attrs[i].getColumn(), attrs[i].getRow(), attrs[i].getColor());	
			}
			
			bir.saveImage(new FileOutputStream("E:/colorAttrTest.bmp"), test);
			System.out.println("Done!");
		}
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		}
	}
}
